<?php

/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2023/10/13 17:03
 * Desc: 美食
 */
class Service_Api_Food extends Contract_Api_Product
{
    /**
     * 类型ID
     */
    const TYPE_ID = 121;

    public function search(array $params = array()): array
    {
        $id        = Arr::get($params, 'id', 0);
        $mid       = Arr::get($params, 'mid', 0);
        $dest_id   = Arr::get($params, 'dest_id', '');
        $sort_type = Arr::get($params, 'sort_type', '');
        $attr_id   = Arr::get($params, 'attr_id', '');
        $category_id   = Arr::get($params, 'category_id', '');//类目
        $keyword   = Arr::get($params, 'keyword', '');
        $lng       = Arr::get($params, 'lng', '');
        $lat       = Arr::get($params, 'lat', '');

        $page     = Arr::get($params, 'page', 1);
        $pagesize = Arr::get($params, 'pagesize', 10);
        $offset   = St_Page::offset($page, $pagesize);

        $params = array(
            'id' => $id,
            'dest_id' => $dest_id,
            'sort_type' => $sort_type,
            'attr_id' => $attr_id,
            'category_id' => $category_id,
            'keyword' => $keyword,
            'lng' => $lng,
            'lat' => $lat,
            'offset' => $offset,
            'pagesize' => $pagesize
        );

        $data = Model_Api_V2_Food::search($params);

        $list = array();
        if (!empty($data['list'])) {
            $marketing_strategy = Model_Api_V2_Marketing_Strategy::get_instance(self::TYPE_ID, array('mid' => $mid));
            $uni_img = Model_Uniapp_Images::get_img_list(self::TYPE_ID);
            foreach ($data['list'] as $v) {
                if(isset($uni_img[$v['id']])){
                    $v['litpic'] = $uni_img[$v['id']];
                }
                $distance = 0;
                if ($lat && $lng) {
                    $distance = Model_Api_V2_Food::get_distance_by_geo($lng, $lat, $v['lat'], $v['lng']);
                }
                $attrname    = Model_Food_Attr::getSecondAttrname($v['attrid']);
                $score       = intval($v['satisfyscore']) / 20 + $v['score'];
                $score       = number_format($score, 1, '.', '');
                $comment_num = Model_Comment::get_comment_num($v['id'], self::TYPE_ID);
                $score_star  = ($score * 10 - ($score * 10 % 5)) / 10;
                $litpic      = Model_Api_V2_System::uniapp_img($v['litpic'], 160, 160);
                $price       = Model_Food::get_minprice($v['id']);

                $list[] = array(
                    'id' => $v['id'],
                    'title' => $v['title'],
                    'comment_num' => $comment_num,
                    'comment_num_str' => $comment_num > 99 ? '99+' : $comment_num,
                    'sell_num' => $v['sell_num'],
                    'sell_num_str' => $v['sell_num'] > 999 ? '999+' : $v['sell_num'],
                    'address' => $v['address'] ?: '',
                    'pay_discount' => $v['pay_discount'] ? floatval($v['pay_discount']) : 0,
                    'maidan_status' => $v['maidan_status'],
                    'renjun' => $v['renjun'] ?: '',
                    'icon_list' => $this->icons($v['iconlist']),
                    'litpic' => $litpic,
                    'price' => $price,
                    'attr_name' => $attrname,
                    'score' => $score,
                    'score_star' => $score_star,
                    'satisfy_score' => St_Functions::get_satisfy(self::TYPE_ID, $v['id'], $v['satisfyscore']),
                    'distance' => $distance,
                    'marketing_strategy' => $marketing_strategy->get_support_application($v['id'])
                );
            }
        }
        $data['list'] = $list;

        return $data;
    }

    public function second_category($params){
        $category = DB::select('attrname','id')
            ->from('food_category');
        if( $params['category_id']){
            $category->where('pid','=', $params['category_id']);
        }else{
            $category->where('pid','>', 0);
        }
        $list = $category->execute()
            ->as_array();
        $list = array_merge(array(array('id'=>0,'attrname'=>'全部')),$list);
        return $list;
    }

    public function info(array $params = array()): array
    {
        /**
         * @var $id
         * @var $lat
         * @var $lng
         * @var $card_suit_id
         */
        extract($params);

        $info = DB::select()
            ->from('food')
            ->where('id', '=', $id)
            ->where('status', '=', 3)
            ->where('ishidden', '=', 0)
            ->execute()
            ->current();
        if (empty($info)) {
            throw new Exception('商品不存在');
        }
        $info['series'] = St_Product::product_series($info['id'], self::TYPE_ID);
        $info['telephone']     = $info['telephone'] ? explode(',', $info['telephone']) : false;
        $info['product_video'] = $info['product_video'] ? $this->img_url((explode('|', $info['product_video'])[0])) : '';
        $distance              = 0;
        if (!empty($lat) && !empty($lng)) {
            $distance = Model_Api_V2_Food::get_distance_by_geo($lng, $lat, $info['lat'], $info['lng']);
        }
        $info['distance']    = $distance;
        $info['attr_name']   = Model_Food_Attr::getSecondAttrname($info['attrid']);
        $score               = intval($info['satisfyscore']) / 20 + $info['score'];
        $info['score']       = number_format($score, 1, '.', '');
        $info['comment_num'] = Model_Comment::get_comment_num($info['id'], self::TYPE_ID);
        $info['score_star']  = ($score * 10 - ($score * 10 % 5)) / 10;
        $info['litpic']      = $this->img_url($info['litpic'], 160, 160);
        $info['piclist']     = $this->pic_list_url($info['piclist']);
        $info['price']       = Model_Food::get_minprice($info['id']);
        $info['sell_num']    = Model_Member_Order_statistic::get_sell_num(self::TYPE_ID, $info['id']);

        // 积分抵现配置
        $jifenprice_info          = Model_Jifen_Price::get_used_jifentprice($info['jifentprice_id'], self::TYPE_ID);
        $info['jifentprice_info'] = $this->filter_data(array('isopen', 'id', 'toplimit', 'jifentprice'), $jifenprice_info);
        // 预定送积分
        $jifenbook_info         = Model_Jifen::get_used_jifenbook($info['jifenbook_id'], self::TYPE_ID);
        $info['jifenbook_info'] = $this->filter_data(array('isopen', 'value', 'rewardway'), $jifenbook_info);
        //积分评论
        $jifencomment_info         = Model_Jifen::get_used_jifencomment(self::TYPE_ID);
        $info['jifencomment_info'] = $this->filter_data(array('isopen', 'value', 'rewardway'), $jifencomment_info);

        $biz_info           = Model_Api_V2_Food::get_biz_time($info['id']);
        $info['biz_time']   = $biz_info['biz_time'];
        $info['biz_status'] = $biz_info['biz_status'];

        $intro_pic_list        = trim($info['intropiclist'], ',');
        $info['intropic_arr']  = $this->pic_list_url($intro_pic_list);

        if ($info['supplierlist']) {
            $supplier_shop_service = new Service_Api_Supplier_Shop();
            $info['supplier_info'] = $supplier_shop_service->get_shop_info($info['supplierlist']);
        }

        // 品牌故事
        $info['description'] = $info['description'] ? $this->content_add_domain($info['description']) : '';

        //套餐信息
        $info['suit_list'] = Model_Api_V2_Food::suit($info['id'], $params);

        //会员折扣
        $info['discount_min_price'] = Model_Api_V2_Discount::get_discount($mid, self::TYPE_ID, $id, $info['price']);

        unset($info['webid']);
        unset($info['aid']);
        unset($info['addtime']);
        unset($info['modtime']);

        return $info;
    }

    public function query_condition(): array
    {


        $data = array(
            'sort' => array(
                array('id' => 0, 'name' => '综合排序'),
                array('id' => 1, 'name' => '价格从低到高'),
                array('id' => 2, 'name' => '价格从高到低'),
                array('id' => 3, 'name' => '销量最高'),
                array('id' => 4, 'name' => '评分最高')
            )
        );

        //属性
        $data['attribute'] = $this->attribute_filter();

        return $data;
    }

    function create_order(array $params = array()): array
    {
        $mid         = $params['mid'];
        $member_info = $params['member_info'];

        list($info, $suit, $extend_data) = Model_Api_V2_Food::check_order_params($params, $mid);

        $order = Model_Api_V2_Food::make_order($params, $info, $suit, $extend_data, $member_info);

        // 处理优惠券
        $coupon_id = Arr::get($params, 'coupon_id', '');
        if ($coupon_id) {
            $coupon_check = Model_Api_V2_Coupon::order_use_coupon_check($coupon_id, $mid, $order);
        }
        /*附加信息*/
        $extend_params = array(
            'member_card_id' => Arr::get($params, 'member_card_id', ''),
            'card_tourist_id' => Arr::get($params, 'card_tourist_id', ''),
        );

        // 判断拼团是否允许使用会员折扣
        if (isset($extend_data['together_info']['discount_limit'])) {
            if (!in_array(2, $extend_data['together_info']['discount_limit'])) {
                $extend_params['use_member_discount'] = false;
            }
        }

        // 保存订单
        $out = Model_Api_V2_Order::add_order($order, 'Model_Food', $extend_params);
        if (!$out || !$out['status']) {
            throw new Exception($out['msg'] ?: '添加订单失败');
        }

        $order_info                 = Model_Member_Order::order_info($order['ordersn']);
        $order_id                   = $order_info['id'];
        $order_info['orderid']      = $order_id;
        $order_info['need_confirm'] = $order['need_confirm'];

        // 优惠券
        if (!empty($coupon_check)) {
            Model_Coupon::add_coupon_order($coupon_check['cid'], $order['ordersn'], $coupon_check['order_total_price'], $coupon_check, $coupon_id);
        }

        // 添加拼团订单
        if (isset($extend_data['together_info'])) {
            Model_Api_V2_Together::add_order($extend_data['together_info'], $order_info);
        }

        // 保存菜品信息
        Model_Api_V2_Food::add_order_dishes($order_id, $suit);

        // 添加发票
        Model_Api_V2_Food::add_bill_info($order_id, $params);

        // 添加红包抵扣
        $envelope_member_id = Arr::get($params, 'envelope_member_id', 0);
        if (St_Functions::is_normal_app_install('red_envelope') && $envelope_member_id) {
            Model_Order_Envelope::order_use_envelope($envelope_member_id, $order['ordersn'], self::TYPE_ID, $mid);
        }

        //订单结算信息表数据更新
        Model_Member_Order_Compute::update($order['ordersn']);

        Hook::trigger('order_created', $order);

        $filter_keys = array('id', 'orderid', 'ordersn', 'pageType', 'typeid', 'status');
        return $this->filter_data($filter_keys, $order_info);
    }

    use Trait_Api_Food;
}